package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import com.zzyl.constant.Constants;
import com.zzyl.properties.JWTConfigProperties;
import com.zzyl.utils.JwtUtil;

import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: Learner
 * @Version: 1.0
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JWTConfigProperties jwtConfigProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求地址。
        String url = request.getRequestURI();
        //2. 判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if (url.contains("login")) {
            log.info("登录请求直接放行");
            return true;
        }
        //1,2步骤可以省略

        //3.获取请求头中的令牌
        String jwt = request.getHeader(Constants.AUTHORIZATION);

        //4.判断令牌是否存在，如果不存在，返回错误结果（未登录）
        if (!StringUtils.hasLength(jwt)) {
            log.info("获取到Jwt令牌为空，返回错误结果");
           response.setStatus(HttpStatus.SC_UNAUTHORIZED);
           return false;
            //throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }

        //5.解析token，如果解析失败，返回错误结果
        try {
            JwtUtil.parseJWT(jwtConfigProperties.getBase64EncodedSecretKey(), jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败，返回错误结果");
           response.setStatus(HttpStatus.SC_UNAUTHORIZED);
           return false;
            //throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);

        }
        //从令牌中获取到用户id，将ID存入线程中
        Claims claims = JwtUtil.parseJWT(jwtConfigProperties.getBase64EncodedSecretKey(), jwt);
        Long ID = MapUtil.get(claims, "id", Long.class);
        UserThreadLocal.set(ID);
        //6，放行
        log.info("令牌正确，放行");
        return true;


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
        log.info("释放了线程");
    }
}
